import React, { FC } from 'react';
import { FormPanel, FormPanelType, InputType, type FormPanelObject, FormPanelBtnAlign, Utils } from 'lfun-bg-comp';
import { Breadcrumb, Button, Table, TableProps, Space } from 'antd';
import _ from 'lodash';
import { useNavigate, useLocation } from 'react-router-dom';
import dayjs from 'dayjs';
import { PageContainer } from '@/component/page-container';
import { SCHOOL_ORG_TYPE } from '@/constant/schoolOptions';
import { PAGINATIONCONFIG } from '@/constant/page';
import { getPagePath, getPathRoot, get_stoge_pz, selectDictLabel, set_stoge_pz } from '@/utils';
import styles from './index.less';
import { APPROVAL_STATUS } from '@/constant';
import { InstitutionParams, searchInstitutionAudit } from '@/service/unit/institution';
import { PageParams } from '@/service';
import { INSTITUTION_TYPE } from '@/constant/institutionOptions';
import PermissionButton, { isPermissionOperate } from '@/component/permission-button';
import useCountry from '@/hooks/useCountry';

const storage_page_size_key = 'other-audit-idx-page-size';

const Groups: FC = () => {
  const [dataSource, setDataSource] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz());
  const [pageIndex, setPageIndex] = React.useState(1);
  const [form, setForm] = React.useState(null);
  const [tableLoading, setTableLoading] = React.useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const country = useCountry();

  const searchTemplate: FormPanelType[] = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      inputs: [
        {
          label: '统一社会信用代码',
          name: 'social_credit_code',
          key: 'social_credit_code',
          textRange: [0, 50],
        },
        {
          label: '机构名称',
          name: 'institution_name',
          key: 'institution_name',
          textRange: [0, 20],
        },
        {
          label: '办别',
          name: 'institution_org_type',
          key: 'institution_org_type',
          inputType: InputType.select,
          renderOption: SCHOOL_ORG_TYPE,
        },
        {
          label: '行政属地',
          name: 'borough',
          key: 'borough',
          inputType: InputType.select,
          renderOption: country,
        },
        {
          label: '所在地区',
          name: 'block',
          key: 'block',
          inputType: InputType.select,
          renderOption: country,
        },
      ],
    },
  ];

  const columns: TableProps['columns'] = [
    {
      title: '机构名称',
      dataIndex: 'institution_name',
      key: 'institution_name',
    },
    {
      title: '机构类型',
      dataIndex: 'institution_category',
      key: 'institution_category',
      render: (text: string) => {
        return selectDictLabel(INSTITUTION_TYPE, text);
      },
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'social_credit_code',
      key: 'social_credit_code',
    },
    {
      title: '法人代表',
      dataIndex: 'leg_repr_name',
      key: 'leg_repr_name',
    },
    {
      title: '成立时间',
      dataIndex: 'create_date',
      key: 'create_date',
      render: (text: any) => {
        if (text) {
          return dayjs(text).format('YYYY-MM-DD');
        }
        return '';
      },
    },
    {
      title: '状态',
      dataIndex: 'approval_status',
      key: 'approval_status',
      width: 100,
      align: 'center',
      render: (text: any, record: any) => _.find(APPROVAL_STATUS, { value: String(text) })?.label,
    },
    {
      title: '审核说明',
      dataIndex: 'reason',
      key: 'reason',
      width: 200,
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'op',
      key: 'op',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => {
        return (
          <Space>
            <PermissionButton permission="view">
              <Button
                key="look"
                type="link"
                size="small"
                onClick={() =>
                  navigate(`${getPathRoot()}/institution-audit/${getProcess_path()}/details/${record.institution_id}`, {
                    state: { ...record },
                  })
                }
              >
                查看
              </Button>
            </PermissionButton>
            {['pending', 'progressing'].includes(record.approval_status) && (
              <PermissionButton permission="approval">
                <Button
                  type="link"
                  size="small"
                  onClick={() =>
                    navigate(
                      `${getPathRoot()}/institution-audit/${getProcess_path()}/details/${record.institution_id}`,
                      {
                        state: { ...record },
                      }
                    )
                  }
                >
                  审核
                </Button>
              </PermissionButton>
            )}
          </Space>
        );
      },
      align: 'center',
    },
  ];
  const getProcess_code = () => {
    const path = location.pathname;
    if (path.includes('institution-audit/open')) {
      return 'i_institution_open';
    }
    if (path.includes('institution-audit/close')) {
      return 'i_institution_close';
    }
    if (path.includes('institution-audit/changekeyinfo')) {
      return 'i_institution_keyinfo_change';
    }
    // TODO: IDEDUBM-662
    // if (path.includes('institute/institution-audit/open')) {
    //   return 'i_institution_open';
    // }
    // if (path.includes('institute/institution-audit/close')) {
    //   return 'i_institution_close';
    // }
    // if (path.includes('institute/institution-audit/changekeyinfo')) {
    //   return 'i_institution_keyinfo_change';
    // }
    // TODO: 
    // if (path.includes('administration/institution-audit/open')) {
    //   return 'i_administration_open';
    // }
    // if (path.includes('administration/institution-audit/close')) {
    //   return 'i_administration_close';
    // }
    // if (path.includes('administration/institution-audit/changekeyinfo')) {
    //   return 'i_administration_close';
    // }

    return '';
  };
  const getProcess_path = () => {
    return {
      i_institution_open: 'open',
      i_institution_close: 'close',
      i_institution_keyinfo_change: 'changekeyinfo',
    }[getProcess_code()];
  };
  const search = async (params: any, pageSize, pageIndex) => {
    if (tableLoading) {
      return;
    }
    setTableLoading(true);
    const searchParams: InstitutionParams & PageParams = {
      ...params,
      process_code: getProcess_code(),
      page: pageIndex,
      per_page: pageSize,
    };
    const { success, data } = await searchInstitutionAudit(searchParams);
    if (success) {
      setDataSource(data.items);
      setTotal(data.total);
      setPageSize(pageSize);
      setPageIndex(pageIndex);
      setTableLoading(false);
    }
  };

  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize);
    search(form?.getFieldsValue(), pageSize, pageIndex);
  };

  React.useEffect(() => {
    if (form && form.resetFields) form.resetFields();
    search({}, pageSize, 1);
  }, [location.pathname]);

  return (
    <PageContainer header={<Breadcrumb items={[{ title: getPagePath().power_name }]} />}>
      <FormPanel
        template={searchTemplate}
        key={1}
        submitBtnText="搜索"
        restBtnText="重置"
        btnsAlign={FormPanelBtnAlign.right}
        onLoad={form => setForm(form)}
        onFinish={(formPanelObject: FormPanelObject) => {
          const params = formPanelObject.getFieldsValue();
          search(params, pageSize, 1);
          setForm(form);
          return false;
        }}
      />
      <Table
        className={styles.table}
        dataSource={dataSource}
        columns={
          Utils.getProps('edu_type') === 'kg' ? columns : columns.filter(it => it.key !== 'planning_school_level')
        }
        scroll={{ x: 'max-content' }}
        loading={tableLoading}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
    </PageContainer>
  );
};

export default Groups;
